package com.ljc.cjgl.service.bbs;

import com.ljc.cjgl.entitiy.bbs.Article;
import com.ljc.cjgl.entitiy.bbs.Comment;
import com.ljc.cjgl.form.bbs.CommentForm;
import com.ljc.cjgl.repository.bbs.ArticleRepository;
import com.ljc.cjgl.repository.bbs.CommentRepository;
import com.ljc.cjgl.security.SysUser;
import com.ljc.cjgl.security.SysUserRepository;
import com.ljc.cjgl.security.User2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: JavaJun
 * Date: 2019-05-05 8:49
 */
@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private ArticleRepository articleRepository;

    public List<Comment> findByArticleId(Integer id) {
        return commentRepository.findByArticleId(id);
    }

    @Transactional
    public synchronized Comment save(CommentForm form) {
        Comment model = new Comment();

        /* 获取帖子对象 */
        Article article = new Article();
        Optional<Article> optional = articleRepository.findById(form.getArticleId());
        if (optional.isPresent()) {
            article = optional.get();
        }
        model.setArticle(article);

        /* 获取当前的登录用户的 username */
        User2 principal = (User2) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = principal.getUsername();
        SysUser user = sysUserRepository.findByUsername(username);
        model.setSysUser(user);

        model.setContent(form.getContent());
        model.setInTime(new Date());
        Comment save = commentRepository.save(model);
        return save;
    }

}
